package com.zeh.bill.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zeh.bill.entity.Dto.UserRoleDTO;
import com.zeh.bill.entity.Role;
import com.zeh.bill.entity.User;
import com.zeh.bill.entity.Vo.RoleQueryVo;
import com.zeh.bill.entity.Vo.UserQueryVo;
import com.zeh.bill.service.RoleService;
import com.zeh.bill.service.UserService;
import com.zeh.bill.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zeh
 * @since 2022-07-18
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RoleService roleService;

    /**
     * 查询所有用户列表
     * @reurn
     */

    @GetMapping("/listAll")
    public Result listAll(){
      return Result.ok(userService.list());
    }

    /**
     * 增加用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public Result add(@RequestBody User user){
        User item = userService.findUserByUserName(user.getUsername());
        if(item != null){
            return Result.error().message("该登录名称已经被使用，请重新输入！");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if(userService.save(user)){
            return Result.ok().message("用户添加成功");
        }
        return Result.error().message("用户添加失败");
    }

    /**
     * 更改用户信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public Result update(@RequestBody User user){
        User item = userService.findUserByUserName(user.getUsername());
        if(item !=null && item.getId()!=user.getId()){
            return Result.error().message("登录名称已被占用！");
        }
        if(userService.updateById(user)){
            return Result.ok().message("用户修改成功");
        }
        return Result.error().message("用户修改失败");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@PathVariable Long id){
        if(userService.deleteById(id)){
            return  Result.ok().message("用户删除成功");
        }
        return Result.error().message("用户删除失败");
    }

    /**
     * 查询用户列表
     * @param userQueryVo
     * @return
     */
    @GetMapping("/list")
    public Result  list(UserQueryVo userQueryVo){
        Page<User> page = new Page<>(userQueryVo.getPageNo(), userQueryVo.getPageSize());
        userService.findUserListByPage(page,userQueryVo);
        return Result.ok(page);
    }

    /**
     * 获取分配角色列表
     * @param roleQueryVo
     * @return
     */
    @GetMapping("/getRoleListForAssign")
    @PreAuthorize("hasAuthority('sys:user:assign')")
    public Result getRoleListForAssign(RoleQueryVo roleQueryVo){
        IPage<Role> page =  new Page<Role>(roleQueryVo.getPageNo(),roleQueryVo.getPageSize());
        roleService.findRoleListByUserId(page,roleQueryVo);
        return Result.ok(page);
    }

    /**
     * 根据用户ID查询该用户拥有的角色列表
     * @param userId
     * @return
     */
    @GetMapping("/getRoleByUserId/{userId}")
    @PreAuthorize("hasAuthority('sys:user:assign')")
    public Result getRoleByUserId(@PathVariable Long userId){
        List<Long> roleIds = roleService.findRoleIdByUserId(userId);
        return Result.ok(roleIds);

    }

    /**
     * 分配角色
     * @param userRoleDTO
     * @return
     */
    @PostMapping("/saveUserRole")
    @PreAuthorize("hasAuthority('sys:user:assign')")
    public Result saveUserRole(@RequestBody UserRoleDTO userRoleDTO){
        if(userService.saveUserRole(userRoleDTO.getUserId(),userRoleDTO.getRoleIds())){
            return Result.ok().message("角色分配成功");
        }
        return Result.error().message("角色分配失败");
    }



}

